<?php
	
/**
 * 微信手机支付类
 */
 include dirname(__FILE__).DIRECTORY_SEPARATOR."wxpay".DIRECTORY_SEPARATOR."WxPayPubHelper.php";
class wxpay
{
	private $db;
	private $config;
	var $parameters; //cft 参数
	public function config($config=null){	
			$this->config=$config;	
	}
   

    /**
     * 生成支付代码
     * @param   array   $order      订单信息
     * @param   array   $payment    支付方式信息
     */
	//支付页面
	
	public function send_pay(){

		session_start();

		$_SESSION['NotifyUrl']=$this->config['NotifyUrl'];
		$_SESSION['paysignkey']=$this->config['paysignkey'];
		$_SESSION['partnerkey']=$this->config['partnerkey'];
		$_SESSION['body']=$this->config['code'];
		$_SESSION['partner']=$this->config['partner'];
		$_SESSION['totol_fee']= $this->config['money'];
		$_SESSION['payType'] = $this->config['payType'];
		//$this->config['money'] = 0.01;
		$state=$this->config['code'].'_'.$this->config['money'].'_'.$this->config['orderType'].'_'.$this->config['payType'];
		//使用jsapi接口
		$jsApi = new JsApi_pub();

		//=========步骤1：网页授权获取用户openid============
		//通过code获得openid
		if (!isset($_GET['code']))
		{
			//触发微信返回code码
			$url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL,$state);
			//echo $url;
			Header("Location: $url"); 
			exit;

		}
    }

  

	/**
	* 设置参数
	*/
	function setParameter($parameter, $parameterValue) {
		$this->parameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
	}

	/**
	* trim
	* @param value
	* @return
	*/
	function trimString($value){
		$ret = null;
		if (null != $value) {
			$ret = $value;
			if (strlen($ret) == 0) {
				$ret = null;
			}
		}
		return $ret;
	}

	//生成随机数
	function create_noncestr( $changdugth = 16 ) {  
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
		$str ="";  
		for ( $i = 0; $i < $changdugth; $i++ )  {  
			$str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
			//$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];  
		}  
		return $str;  
	}
	
	//参数判断
	function check_cft_parameters(){
		if($this->parameters["bank_type"] == null || $this->parameters["body"] == null || $this->parameters["partner"] == null || 
			$this->parameters["out_trade_no"] == null || $this->parameters["total_fee"] == null || $this->parameters["fee_type"] == null ||
			$this->parameters["notify_url"] == null || $this->parameters["spbill_create_ip"] == null || $this->parameters["input_charset"] == null
			)
		{
			return false;
		}
		return true;
	}

	//生成package
	protected function get_cft_package(){
		try {
			if (null == $this->parameters['wxpay_partnerkey'] || "" == $this->parameters['wxpay_partnerkey']) {
				throw new Exception("密钥不能为空！" . "<br>");
			}
			ksort($this->parameters);
			$unSignParaString = $this->formatQueryParaMap($this->parameters, false);
			$paraString = $this->formatQueryParaMap($this->parameters, true);

			return $paraString . "&sign=" . $this->sign($unSignParaString,$this->trimString($this->parameters['wxpay_partnerkey']));
		}catch (Exception $e)
		{
			die($e->getMessage());
		}

	}
	protected function get_biz_sign($bizObj){
		 foreach ($bizObj as $k => $v){
			 $bizParameters[strtolower($k)] = $v;
		 }
		 try {
		 	if($this->parameters['wxpay_paysignkey'] == ""){
		 			throw new Exception("APPKEY为空！" . "<br>");
		 	}
		 	$bizParameters["appkey"] = $this->parameters['wxpay_paysignkey'];
		 	ksort($bizParameters);
		 	//var_dump($bizParameters);
		 	$bizString = $this->formatBizQueryParaMap($bizParameters, false);
		 	//var_dump($bizString);
		 	return sha1($bizString);
		 }catch (Exception $e)
		 {
			die($e->getMessage());
		 }
	}
	
	
	function formatQueryParaMap($paraMap, $urlencode){
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v){
			if (null != $v && "null" != $v && "sign" != $k) {
			    if($urlencode){
				   $v = urlencode($v);
				}
				$buff .= $k . "=" . $v . "&";
			}
		}
		$reqPar;
		if (strlen($buff) > 0) {
			$reqPar = substr($buff, 0, strlen($buff)-1);
		}
		return $reqPar;
	}
	function formatBizQueryParaMap($paraMap, $urlencode){
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v){
		//	if (null != $v && "null" != $v && "sign" != $k) {
			    if($urlencode){
				   $v = urlencode($v);
				}
				$buff .= strtolower($k) . "=" . $v . "&";
			//}
		}
		$reqPar;
		if (strlen($buff) > 0) {
			$reqPar = substr($buff, 0, strlen($buff)-1);
		}
		return $reqPar;
	}
	
	//md5
	function sign($content, $key) {
	    try {
		    if (null == $key) {
			   throw new Exception("财付通签名key不能为空！" . "<br>");
		    }
			if (null == $content) {
			   throw new Exception("财付通签名内容不能为空" . "<br>");
		    }
		    $signStr = $content . "&key=" . $key;
		
		    return strtoupper(md5($signStr));
		}catch (Exception $e)
		{
			die($e->getMessage());
		}
	}
	
	function verifySignature($content, $sign, $md5Key) {
		$signStr = $content . "&key=" . $md5Key;
		$calculateSign = strtolower(md5($signStr));
		$tenpaySign = strtolower($sign);
		return $calculateSign == $tenpaySign;
	}

	
	function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
        	 if (is_numeric($val))
        	 {
        	 	$xml.="<".$key.">".$val."</".$key.">"; 

        	 }
        	 else
        	 	$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";  
        }
        $xml.="</xml>";
        return $xml; 
    }

	//生成jsapi支付请求json
	/*
	"appId" : "wxf8b4f85f3a794e77", //公众号名称，由商户传入
	"timeStamp" : "189026618", //时间戳这里随意使用了一个值
	"nonceStr" : "adssdasssd13d", //随机串
	"package" : "bank_type=WX&body=XXX&fee_type=1&input_charset=GBK&notify_url=http%3a%2f
	%2fwww.qq.com&out_trade_no=16642817866003386000&partner=1900000109&spbill_create_i
	p=127.0.0.1&total_fee=1&sign=BEEF37AD19575D92E191C1E4B1474CA9",
	//扩展字段，由商户传入
	"signType" : "SHA1", //微信签名方式:sha1
	"paySign" : "7717231c335a05165b1874658306fa431fe9a0de" //微信签名
	*/
	function create_biz_package(){
		 try {
			if($this->check_cft_parameters() == false) {   
			   throw new Exception("生成package参数缺失！" . "<br>");
		    }
		    $nativeObj["appId"] = 'wxae86b990f42188ed';
		    $nativeObj["package"] = $this->get_cft_package();
		    $nativeObj["timeStamp"] = strval(time());
		    $nativeObj["nonceStr"] = $this->create_noncestr();
		    $nativeObj["paySign"] = $this->get_biz_sign($nativeObj);
		    $nativeObj["signType"] = $this->parameters['wxpay_signtype'];
		   
		    return json_encode($nativeObj);
		   
		}catch (Exception $e)
		{
			die($e->getMessage());
		}		   
		
	}
	
}
	/* 微信认证通过， 开始回调 */
	if (isset($_GET['code'])&&isset($_GET['state']))
	{
		$jsApi = new JsApi_pub();
		$state=$_GET['state'];
		//echo $state;
		$lines = array();
		$lines = explode("_", $state);
		$out_trade_no=$lines[0];
		$totol_fee=$lines[1];
		$orderType = $lines[2];
		$payType = $lines[3];
		//echo $out_trade_no;
		//echo("HHH");
		//echo $totol_fee;

		$db_config = include(dirname(dirname(dirname(dirname(__FILE__))))."/database/database.inc.php");
		$db_config = $db_config['default'];
		$db_con = mysqli_connect($db_config['hostname'],$db_config['username'],$db_config['password'],$db_config['database']); 
		// 设置显示字符集
		$sql = "set names utf8";
		// 执行sql语句
		mysqli_query($db_con,$sql);
		$sql = "select * from `yys_yonghu_addmoney_record` where `code` = '$out_trade_no' limit 1";
		$result = mysqli_query($db_con,$sql);
		$row = $result->fetch_assoc();
		//print_r($row);
		$isZhongChou = $row['is_zhongchou'];

	    $code = $_GET['code'];
		$jsApi->setCode($code);
		$openid = $jsApi->getOpenId();
		//echo $openid;
		//echo("YYY");
		//=========步骤2：使用统一支付接口，获取prepay_id============
		//使用统一支付接口
		$unifiedOrder = new UnifiedOrder_pub();
		//设置统一支付接口参数
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//spbill_create_ip已填,商户无需重复填写
		//sign已填,商户无需重复填写
		
		$unifiedOrder->setParameter("openid",$openid);//商品描述
		$unifiedOrder->setParameter("body",$out_trade_no);//商品描述
		//自定义订单号，此处仅作举例
		//$timeStamp = time();
		//$out_trade_no = WxPayConf_pub::APPID."$timeStamp";
		$unifiedOrder->setParameter("out_trade_no",$out_trade_no);//商户订单号 
		$NotifyUrl=WxPayConf_pub::NOTIFY_URL;
		$unifiedOrder->setParameter("total_fee",$totol_fee*100);//总金额
		//$unifiedOrder->setParameter("total_fee",$totol_fee);//总金额
		$unifiedOrder->setParameter("notify_url",$NotifyUrl);//通知地址 
		$unifiedOrder->setParameter("trade_type","JSAPI");//交易类型

		//非必填参数，商户可根据实际情况选填
		//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
		//$unifiedOrder->setParameter("device_info","XXXX");//设备号 
		//$unifiedOrder->setParameter("attach","XXXX");//附加数据 
		//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
		//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
		//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记 
		//$unifiedOrder->setParameter("openid","XXXX");//用户标识
		//$unifiedOrder->setParameter("product_id","XXXX");//商品ID

		$prepay_id = $unifiedOrder->getPrepayId();
		//echo "<meta charset='utf-8'>";
		//print_r("准备发起微信jsapi支付");
		//=========步骤3：使用jsapi调起支付============
		$jsApi->setPrepayId($prepay_id);
		$jsApiParameters = $jsApi->getParameters();
		//echo $jsApiParameters ;
		//print_r("微信jsapi支付完成");
		include('shouji.php');
		ob_end_flush();
		exit;
	
	}



?>